package it.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 登录验证的过滤器，如果没有登录，无法访问数据
 *
 * @author wsx
 * @create 2020-04-22-11:44
 */
@WebFilter("/*")
public class loginFilter implements Filter {
    public void destroy() {
    }
    public void init(FilterConfig config) throws ServletException {}
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强制转换 使用servletrequest的子类
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获取资源请求路径
        String uri = request.getRequestURI();
        //判断是否包含登录相关资源
        if (uri.contains("Login.html") || uri.contains("Register.html") || uri.contains("/img/") || uri.contains("/layui/")
                || uri.contains("/statics/") || uri.contains("/bootstrap-3.3.7-dist") || uri.contains("/checkLogin") || uri.contains("/checkManagerLogin")
                || uri.contains("/isExistUser") || uri.contains("/isExistUserPass") || uri.contains("/regService")) {
            //如果包含登录相关信息，则放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //从session中获取user
            Object user = request.getSession().getAttribute("user");
            if (user != null) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                //没有登录，返回登录页面
                request.setAttribute("loginmsg","您尚未登录，请先登录！");
                request.getRequestDispatcher("Login.html").forward(servletRequest,servletResponse);
            }
        }
        //chain.doFilter(req, resp);
    }
}
